<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
// @ts-ignore
import { WriteClients } from '@/Urls/AxiosHelper'

const router = useRouter()

const formRef = ref()
const form = reactive({
  materialCode: '', // 物料编号
  autoCode: false,  // 系统编号开关
  materialName: '',
  unit: '',
  spec: '',
  materialType: '',
  materialAttr: '',
  materialClass: '',
  status: true,
  validPeriod: undefined as number | undefined,
  warnAdvanceDays: undefined as number | undefined,
  warnEnable: true,
  stockUpper: undefined as number | undefined,
  stockLower: undefined as number | undefined,
  purchasePrice: undefined as number | undefined,
  remark: '',
  image: '',
  attachment: '',
})

const rules = {
  materialCode: [{ required: true, message: '请输入物料编号', trigger: 'blur' }],
  materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  unit: [{ required: true, message: '请选择单位', trigger: 'change' }],
  materialType: [{ required: true, message: '请选择物料类型', trigger: 'change' }],
  materialAttr: [{ required: true, message: '请选择物料属性', trigger: 'change' }],
  materialClass: [{ required: true, message: '请选择物料分类', trigger: 'change' }],
  stockUpper: [
    { required: true, message: '请输入库存上限', trigger: 'blur' },
    { validator: validateStockUpper, trigger: 'blur' }
  ],
  stockLower: [
    { required: true, message: '请输入库存下限', trigger: 'blur' },
    { validator: validateStockLower, trigger: 'blur' }
  ],
  purchasePrice: [{ required: true, message: '请输入采购价格', trigger: 'blur' }],
}

const unitOptions = ['件','个','箱','台','米']
const typeOptions = ['原料','半成品','成品','其他']
const attrOptions = ['自制','委外','外购','其他']
const classOptions = ['A类','B类','C类']

// 验证函数
function validateStockUpper(rule: any, value: any, callback: any) {
  if (value !== undefined && form.stockLower !== undefined && value <= form.stockLower) {
    callback(new Error('库存上限必须大于库存下限'))
  } else {
    callback()
  }
}

function validateStockLower(rule: any, value: any, callback: any) {
  if (value !== undefined && form.stockUpper !== undefined && value >= form.stockUpper) {
    callback(new Error('库存下限必须小于库存上限'))
  } else {
    callback()
  }
}

const writeClient = WriteClients[3]
const imageUrl = ref<string>('')
const attachmentUrl = ref<string>('')
const attachmentName = ref<string>('')

async function uploadImage(option:any){
  try{
    const fd = new FormData()
    fd.append('file', option.file)
    const res = await writeClient.post('/api/Upload/UploadImg', fd, { headers:{ 'Content-Type':'multipart/form-data' } })
    const url = res?.data?.data || ''
    imageUrl.value = url
    form.image = url
    option?.onSuccess && option.onSuccess(res.data)
  }catch(err:any){
    option?.onError && option.onError(err)
    ElMessage.error(err?.response?.data?.message || err?.message || '图片上传失败')
  }
}

async function uploadAttachment(option:any){
  try{
    const fd = new FormData()
    fd.append('file', option.file)
    const res = await writeClient.post('/api/Upload/UploadCompanyFile', fd, { headers:{ 'Content-Type':'multipart/form-data' } })
    const url = res?.data?.data || ''
    attachmentUrl.value = url
    attachmentName.value = option.file?.name || '文件'
    form.attachment = url
    option?.onSuccess && option.onSuccess(res.data)
  }catch(err:any){
    option?.onError && option.onError(err)
    ElMessage.error(err?.response?.data?.message || err?.message || '文件上传失败')
  }
}

function generateGuid(){
  const s = '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c: string) =>
    (Number(c) ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> Number(c) / 4).toString(16)
  )
  return s
}
watch(()=>form.autoCode,(v)=>{ if(v){ form.materialCode = generateGuid() } })

async function handleSave(){
  // @ts-ignore
  formRef.value?.validate(async (ok:boolean)=>{
    if(!ok) return
    try{
      const payload = {
        productNumber: form.materialCode, // 后端字段沿用产品命名时，统一映射
        productName: form.materialName,
        specificationModel: form.spec,
        unit: form.unit,
        productType: form.materialType,
        productAttribute: form.materialAttr,
        productClassification: form.materialClass,
        activationStatus: form.status,
        validDate: form.validPeriod ?? 0,
        alarmDays: form.warnAdvanceDays ?? 0,
        maximumInventoryLevel: form.stockUpper ?? 0,
        minimumInventoryLevel: form.stockLower ?? 0,
        purchasePrice: form.purchasePrice ?? 0,
        remarks: form.remark || '',
        image: form.image || '',
        attachment: form.attachment || '',
      }
      const res = await writeClient.post('/api/Material/CreateMaterial', payload)
      if(res && (res.status===200 || res?.data?.code===200 || res?.data?.success)){
        ElMessage.success('保存成功')
        router.push({ name: 'MaterialInfo' })
      }else{
        throw new Error(res?.data?.message || '保存失败')
      }
    }catch(err:any){
      ElMessage.error(err?.response?.data?.message || err?.message || '保存失败')
    }
  })
}

function handleCancel(){ router.push({ name: 'MaterialInfo' }) }
</script>

<template>
  <div class="create-wrap">
    <el-card class="top-card">
      <template #header>
        <div class="header-row">
          <div class="title">新增物料</div>
          <div class="spacer"></div>
        </div>
      </template>

      <div class="section-title">基础信息</div>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="96px" class="base-form">
        <div class="grid">
          <div class="col">
            <el-form-item label="物料编号" prop="materialCode">
              <div class="inline">
                <el-input v-model="form.materialCode" placeholder="请输入" style="width:260px" />
                <div class="gap-12"></div>
                <span class="muted">系统编号</span>
                <el-switch v-model="form.autoCode" inline-prompt />
              </div>
            </el-form-item>
            <el-form-item label="规格型号">
              <el-input v-model="form.spec" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="物料类型">
              <el-select v-model="form.materialType" placeholder="选择类型">
                <el-option v-for="o in typeOptions" :key="o" :label="o" :value="o" />
              </el-select>
            </el-form-item>
            <el-form-item label="物料分类">
              <el-select v-model="form.materialClass" placeholder="选择分类">
                <el-option v-for="o in classOptions" :key="o" :label="o" :value="o" />
              </el-select>
            </el-form-item>
            <el-form-item label="有效期">
              <div class="inline">
                <el-input-number v-model="form.validPeriod" :min="0" :max="99999" />
                <div class="gap-8"></div>
                <span class="muted">天</span>
                <div class="gap-24"></div>
                <el-checkbox v-model="form.warnEnable" />
              </div>
            </el-form-item>
            <el-form-item label="库存上限" prop="stockUpper">
              <el-input-number v-model="form.stockUpper" :min="0" />
            </el-form-item>
            <el-form-item label="采购价格" prop="purchasePrice">
              <el-input-number v-model="form.purchasePrice" :precision="2" :step="0.1" :min="0" />
            </el-form-item>
            <el-form-item label="备注" class="remark-item">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入" />
            </el-form-item>
          </div>

          <div class="col">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="单位" prop="unit">
              <el-select v-model="form.unit" placeholder="请选择单位">
                <el-option v-for="o in unitOptions" :key="o" :label="o" :value="o" />
              </el-select>
            </el-form-item>
            <el-form-item label="物料属性" prop="materialAttr">
              <el-select v-model="form.materialAttr" placeholder="请选择属性">
                <el-option v-for="o in attrOptions" :key="o" :label="o" :value="o" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="true">启用</el-radio>
                <el-radio :label="false">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="报警天数">
              <div class="inline">
                <span class="muted">提前</span>
                <div class="gap-8"></div>
                <el-input-number v-model="form.warnAdvanceDays" :min="0" :max="99999" />
                <div class="gap-8"></div>
                <span class="muted">天报警</span>
              </div>
            </el-form-item>
            <el-form-item label="库存下限" prop="stockLower">
              <el-input-number v-model="form.stockLower" :min="0" />
            </el-form-item>
          </div>
        </div>
      </el-form>
    </el-card>

    <el-card class="section-card">
      <template #header>
        <div class="section-title">图片</div>
      </template>
      <div class="image-row">
        <div class="left">
          <el-upload :http-request="uploadImage" :show-file-list="false" accept="image/*">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </div>
        <div class="right">
          <el-image v-if="imageUrl" :src="imageUrl" fit="contain" style="width: 240px; height: 160px; border:1px dashed #e5e7eb; border-radius:6px;" />
          <div v-else class="img-empty">暂无图片</div>
        </div>
      </div>
    </el-card>

    <el-card class="section-card">
      <template #header>
        <div class="section-title">附件</div>
      </template>
      <el-upload drag :http-request="uploadAttachment" :show-file-list="false" class="attach-drag">
        <i class="el-icon--upload"></i>
        <div class="el-upload__text">点击或将文件拖到此区域上传</div>
        <template #tip>
          <div class="el-upload__tip">支持 docx, xls, PDF, rar, zip, PNG, JPG 等类型的文件</div>
        </template>
      </el-upload>
      <div v-if="attachmentUrl" class="file-line">
        <el-link :href="attachmentUrl" target="_blank" type="primary" underline="hover">{{ attachmentName || '下载附件' }}</el-link>
      </div>
    </el-card>

    <el-card class="section-card">
      <div class="op-bottom">
        <el-button size="large" @click="handleCancel">返回列表</el-button>
        <el-button size="large" type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.create-wrap{ display:flex; flex-direction:column; gap:12px; }
.header-row{ display:flex; align-items:center; }
.title{ font-size:20px; font-weight:700; }
.spacer{ flex:1; }
.section-title{ text-align:center; color:#606266; }
.base-form{ margin-top:8px; }
.grid{ display:grid; grid-template-columns: 1fr 1fr; column-gap:24px; }
.col{ display:flex; flex-direction:column; gap:12px; }
.inline{ display:flex; align-items:center; }
.gap-8{ width:8px; }
.gap-12{ width:12px; }
.gap-24{ width:24px; }
.muted{ color:#909399; font-size:12px; }
.remark-item :deep(textarea){ min-height:84px; }

.image-row{ display:flex; gap:16px; }
.image-row .left{ display:flex; align-items:flex-start; gap:12px; }
.image-row .right{ flex:1; min-height:120px; background: #fff; border:1px dashed #e5e7eb; border-radius:6px; }

.attach-drag{ width:100%; }
.section-card :deep(.el-card__header){ text-align:center; }
.img-empty{ width:240px; height:160px; display:flex; align-items:center; justify-content:center; color:#999; background:#f8f9fb; border:1px dashed #e5e7eb; border-radius:6px; }
.file-line{ margin-top:8px; }
.op-bottom{ display:flex; justify-content:center; gap:16px; }
</style>


